package boss.portal.service.impl;

import boss.portal.entity.CustomerUserDetails;
import boss.portal.entity.User;
import boss.portal.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaoxinguo on 2017/9/13.
 * 自己实现UserDetailService,用与SpringSecurity获取用户信息
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserRepository userRepository;

    /**
     * 通过构造器注入UserRepository
     *
     * @param userRepository
     */
    public UserDetailsServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new BadCredentialsException(username);
        }

        CustomerUserDetails customerUserDetails = new CustomerUserDetails(user);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //用于添加用户的权限。实际应该查询数据角色添加进去，此处我们模拟。
        for (int i = 0; i < 5; i++) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + i));
        }
        customerUserDetails.setAuthorities(authorities);
        log.info("authorities:{}", authorities);
        //这里返回的是我们自己定义的UserDetail
        return customerUserDetails;
    }

}
